package registry_controller

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"shimmer/neusoft_club_backend/dao/domain"
	"shimmer/neusoft_club_backend/services"
	"shimmer/neusoft_club_backend/services/assets_service"
	"time"
)

type accountPasswordRegistry struct {
	Account  string     `json:"account" form:"account" xml:"account" binding:"required"`
	Password string     `json:"password" form:"password" xml:"password" binding:"required"`
	Nickname string     `json:"nickname" form:"nickname" xml:"nickname" binding:"required"`
	Gender   *int       `json:"gender" form:"gender" xml:"gender"`
	Avatar   *string    `json:"avatar" form:"avatar" xml:"avatar"`
	Birthday *time.Time `json:"birthday" form:"birthday" xml:"birthday"`
	Name     *string    `json:"name" form:"name" xml:"name"`
	Email    *string    `json:"email" form:"email" xml:"email"`
	Wechat   *string    `json:"wechat" form:"wechat" xml:"wechat"`
	QQ       *string    `json:"qq" form:"qq" xml:"qq"`
	Comment  *string    `json:"comment" form:"comment" xml:"comment"`
}

// @Summary 注册账号
// @Description 使用账号密码注册账号
// @Tags 注册
// @Param account body registry_controller.accountPasswordRegistry true "account"
// @Success 200
// @Router /api/registry/ap [post]
func accountPasswordRegistration(c *gin.Context) {
	registry := accountPasswordRegistry{}
	err := c.ShouldBind(&registry)
	if err != nil {
		services.AbortWithError(c, err)
		return
	}
	registry.Password, err = domain.HashPassword(registry.Password)
	if err != nil {
		services.AbortWithError(c, err)
		return
	}
	err = services.DBEngine.Transaction(func(tx *gorm.DB) (err error) {
		var assetsId *int64 = nil
		if registry.Avatar != nil {
			// call assets_service API to upload avatar and return assets_service id
			assets, err := assets_service.CreateForeignAssets(*registry.Avatar, tx)
			if err != nil {
				return err
			}
			assetsId = &assets.ID
		}
		var gender int32
		if registry.Gender == nil {
			gender = 0
		} else {
			gender = int32(*registry.Gender)
		}
		newUser := domain.User{
			Nickname: registry.Nickname,
			Name:     registry.Name,
			Gender:   domain.UserGender(gender),
			Birthday: registry.Birthday,
			Wechat:   registry.Wechat,
			QQ:       registry.QQ,
			Comment:  registry.Comment,
			AvatarID: assetsId,
		}

		err = tx.Save(&newUser).Error

		if err != nil {
			services.AbortWithError(c, err)
			return
		}

		account := domain.Account{
			UserID:   &newUser.ID,
			Account:  &registry.Account,
			Password: &registry.Password,
		}
		err = tx.Save(&account).Error
		if err != nil {
			services.AbortWithError(c, err)
			return
		}
		return
	})
	if err != nil {
		return
	}

	c.JSON(200, gin.H{
		"success": true,
	})
}

func ConfigRegistryController(groupConfig *gin.RouterGroup) {
	groupConfig.POST("/ap", accountPasswordRegistration)
}
